package com.klun.concTrueWar.eleven;

/**
 * 程序清单 11-8 在基于散列的 Map 中使用锁分段技术 线程安全
 */
public class StripedMap {
    private static final int N_LOCKS = 16;
    private final Node[] buckets;
    private final Object[] locks;

    public StripedMap(int numBuckets) {
        this.buckets = new Node[numBuckets];
        locks = new Object[N_LOCKS];
        for (int i = 0; i < N_LOCKS; i++) {
            locks[i] = new Object();
        }
    }

    private static class Node{
        public String key;
        public String value;
        public Node next;
    }

    private final int hash(Object key){
        return Math.abs(key.hashCode() % buckets.length);
    }
    public Object get(Object key){
        int hash = hash(key);
        synchronized (locks[hash % N_LOCKS]){
            for(Node m = buckets[hash]; m!=null;m=m.next){
                if(m.key.equals(key)){
                    return m.value;
                }
            }
        }
        return null;
    }
    public void clear(){
        for (int i = 0; i < buckets.length; i++) {
            synchronized (locks[i % N_LOCKS]){
                buckets[i] =null;
             }
        }
    }

}
